package com.qing.library.services;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;

import com.qing.library.utils.L;
import com.qing.library.utils.NetWorkUtil;

public class ListenerNetStateService extends Service {

    private int num = 0;
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION) || action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {

                Log.e("main_A","***网络状态已经改变***");
                ConnectivityManager connectivityManager =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                NetworkInfo activeInfo = connectivityManager.getActiveNetworkInfo();
//                if (activeInfo.isConnected()) {NetWorkUtil.NETWORK = true;Log.e("main_A","activeInfo___connect");}
                try{Log.e("main_A","是否连接：" + activeInfo.isConnected());}catch (Exception e){Log.e("main_A","连接异常");}
                if(!wifiInfo.isConnected() && !mobileInfo.isConnected()){

                    NetWorkUtil.NETWORK=false;
                    Log.e("main_A","没有可用网络");
                }else{
                    NetWorkUtil.NETWORK=true;
                    NetWorkUtil.WIFI=true;
                    Log.e("main_A","当前网络名称：" + activeInfo.getTypeName());
                }
            }
        }
    };

    @Override

    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() {

        super.onCreate();
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, mFilter);
        L.e("main_A","网络状态——监听：开始");
    }

    @Override
    public void onDestroy() {

        unregisterReceiver(mReceiver);
        Log.e("main_A","网络状态——监听：结束");
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }
}
